import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login/index'
import Layout from '@/views/layout/index'
import Dashboard from '@/views/dashboard/index'
import Article from '@/views/article/index'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      { path: 'dashboard', component: Dashboard },
      { path: 'article', component: Article }
    ]
  }
]

const router = new VueRouter({
  // mode: 'history',
  routes
})

// 白名单
const whiteList = ['/login']

// 全局前置守卫： 页面一发生跳转 都会执行全局前置守卫
// to: 到哪儿去
// from:从哪儿来
// next: 放行||重新跳转新页面  必须要执行
router.beforeEach((to, from, next) => {
  // console.log('to', to)
  // console.log('from', from)
  // 注意：token的获取一定要在beforeEach内部获取
  const token = store.state.user.token
  if (token) {
    // 有token的情况
    if (to.path === '/login') {
      // 有token访问的是登录页 跳转到首页
      next('/')
    } else {
      // 有token访问的不是登录页 直接方向
      next()
    }
  } else {
    // 没有token的情况
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
